import { getMenuList } from '@/api/index'
import { Reducer, Effect, Subscription, history } from 'umi'
import { ResultType } from '@/types/index'
import { getTreeData, setStorage } from '@/utils'

export interface MenuItemType {
  code: string
  name: string
  parentCode: string
  status: number
  url: string
  children: []
}

export interface LayoutStateType {
  menuList: MenuItemType[]
}
interface LayoutModelType {
  namespace: string
  state: LayoutStateType
  reducers: {
    setState: Reducer<LayoutStateType>
  }
  effects: {
    function_getMenuList: Effect
  }
  subscriptions: {
    setup: Subscription
  }
}

export default <LayoutModelType>{
  namespace: 'layoutmodel',
  state: {
    menuList: []
  },
  reducers: {
    setState(state, { payload }) {
      return { ...state, ...payload }
    }
  },
  effects: {
    *function_getMenuList({ callback }, { call, put }) {
      const res: ResultType = yield call(getMenuList)
      if (res.code === 200) {
        ;(res.obj as any).forEach((item: any) => {
          if (item.name === '指标赋分') {
            item.url = item.url.replace('evaluation', 'assignment')
            let type = item.url.split('?')[1].split('=')[1]
            setStorage('type', type)
          }
        })

        const result: MenuItemType[] = getTreeData(res.obj as MenuItemType[])
        yield put({
          type: 'setState',
          payload: {
            menuList: result
          }
        })
        callback(res)
      }
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {}
  }
}
